<?php
	/* -------------------------------------------------------------------
	IOU - expense sharing system 
	Copyright (C) 2009-2013 - Mischa Spelt (m.spelt@gmail.com)
	
	This program is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.
	
	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.
	
	You should have received a copy of the GNU General Public License
	along with this program.  If not, see <http://www.gnu.org/licenses/>.
	
	------------------------------------------------------------------- */

	include_once("lib/lib.main.php");
	checklogin();
	print_header("Bill");

	$billID = $_REQUEST['id'];
	if(isset($_POST['update'])) {
		if($_POST['id'] == "new") 
		{
			$billID = $db->q("returnid INSERT INTO Bills(Date, Description, GroupID, CreatedBy, IsPrivate) VALUES(%s, %s, %i, %i, %i)", $_POST['date'], stripslashes($_POST['description']), $_POST['group'], $gUser['ID'], $_POST['isprivate'] ? -1 : 0);
		}
		else
		{
			$db->q("UPDATE Bills SET Date = %s, Description = %s, IsPrivate = %i WHERE ID = %i", $_POST['date'], stripslashes($_POST['description']), $_POST['isprivate'] ? -1 : 0, $billID);
		}
	}

	define(denyAccessMessage, "<h1>Access denied</h1><table class='center'><tr><td><p>You are not allowed to view this bill. The reason may be one of the following: <ul><li>The ID you entered does not correspond to a valid bill.</li><li>The bill you requested is not assigned to a group of which you are a member.</li><li>The bill was marked as private and you are not involved.</li></ul></p></td></tr></table>");
	$bill = $db->q("maybetuple SELECT * FROM Bills WHERE ID = %i", $billID);
	$isNew = false;
	// If the bill is not found but an ID was given, print error
	if(!$bill)
		if(isset($_REQUEST['id'])) {
			print denyAccessMessage;
			exit;
		}
		// If no active bill and no ID given, create a new one
		else
			$isNew = true;

	if($bill) {
		// Deny access if the user is not in the bill group
		if($db->q("value SELECT COUNT(*) FROM Users_Groups WHERE UserID = %i AND GroupID = %i", $gUser['ID'], $bill['GroupID']) == 0) {
			print denyAccessMessage;
			exit;
		}
		// Deny access if the bill is private, and user is not the creator or in the journal of this bill
		if($bill['IsPrivate'] && !($bill['CreatedBy'] == $gUser['ID'] || $db->q("value SELECT COUNT(*) FROM Journal WHERE BillID = %i AND UserID = %i", $bill['ID'], $gUser['ID']) > 0)) {
			print denyAccessMessage;
			exit;
		}
	}

	if(!$isNew && isset($_POST['savenew'])) {
		foreach($_POST['newlines'] as $line) {
			if(abs($line['Amount']) > 0.01) 
				$db->q("INSERT INTO Journal(BillID, UserID, Description, Amount, Divisor, IsPayment) VALUES(%i, %i, %s, %f, %i, %i)", $billID, $line['UserID'], $line['Description'], $line['IsPayment'] ? -$line['Amount'] : $line['Amount'], $line['Divisor'], $line['IsPayment']);
		}
		unset($_POST);
	}	


	print "<h1>" . ($isNew ? "Enter new bill" : "Edit bill") . "</h1>";
	print "<form method='post' action='$PHP_SELF?id=$billID'><table>";
	print "<input type='hidden' name='id' value='" . ($isNew ? "new" : $billID) . "'>";
	print "<tr><td><label for='date' accesskey='D'><span class='accesskey'>D</span>ate</label></td><td><input type='text' size='10' name='date' id='date' value='" . ($isNew ? date('Y-m-d') : $bill['Date']) . "'> (yyyy-mm-dd)</td></tr>";
	print "<tr><td><label for='description' accesskey='E'>D<span class='accesskey'>e</span>scription</label></td><td><input type='text' maxlength='50' name='description' id='description' value=\"" . stripslashes($bill['Description']) . "\"></td></tr>";
	print "<tr><td>" . ($isNew ? "<label for='group' accesskey='P'>Grou<span class='accesskey'>p</span></label>" : "Group") . "</td><td>";
	if($isNew) {
		print "<select name='group' id='group'>";
		foreach($myGroups = $db->q("table SELECT ID, DisplayName FROM Groups LEFT JOIN Users_Groups ON GroupID = ID WHERE UserID = %i ORDER BY (ID = %i) DESC, DisplayName ASC", $gUser['ID'], $gUser['PreferredGroup']) as $group) print "<option value={$group['ID']}'>{$group['DisplayName']}</option>";
		print "</select>";
	}
	else
		print $db->q("value SELECT DisplayName FROM Groups WHERE ID = %i", $bill['GroupID']);
	print "</td></tr>";
	if(!$isNew)
		print "<tr><td>Entered by</td><td>" . $db->q("value SELECT DisplayName FROM Users WHERE ID = %i", $bill['CreatedBy']) . "</td></tr>";
	if($bill['IsRepayment'])
		print "<tr><td>Repayment:</td><td> <input type='checkbox' checked='checked' disabled='disabled' /> This is a settlement of a debt between the users below.</td></tr>";
	print "<tr><td><span class='accesskey'>P</span>rivate bill?</td><td><input type='checkbox'" . ($bill['IsPrivate'] ? " checked='checked'" : "") . " id='isprivate' name='isprivate' value='-1' accesskey='P' /> <label for='isprivate'>The bill is only visible for the users involved.</label></td></tr>";
	print "<tr><td colspan='2' style='text-align: center;'><input type='submit' name='update' value='" . ($isNew ? "Save new bill and enter details" : "Save details") . "'></td></tr>";
	print "</table></form>";

	if(!$isNew):
		// Existing lines
		print "<h1>Bill details</h1>";
		print "<table class='center'>";
		$i = $divisor = 1;
		foreach($db->q("table SELECT DisplayName, Description, Amount, Divisor, IsPayment FROM Journal LEFT JOIN Users ON Journal.UserID = Users.ID WHERE Journal.BillID = %i", $billID) as $line) {
			if(--$divisor == 0) { $divisor = $line['Divisor']; $i++; }
			$amountCell = "<td style='width: 5em;' title='" . ($line['Divisor'] != 1 ? "1/{$line['Divisor']} x " . money_format(moneyFormat, $line['Amount']) : "") . "'> " . money_format(moneyFormat, abs($line['Amount'] / $line['Divisor'])) . "</td>";
			print "<tr" . ($i % 2 ? " class='gray'" : "") . ($line['IsPayment'] ? " style='color: blue;'" : "") . "><td style='width: 5em;'>" . ($bill['IsRepayment'] ? "" : ($line['IsPayment'] ? "Contrib." : "Charge")) . "</td><td style='width: 10em;'>{$line['DisplayName']}</td><td>{$line['Description']}</td>" . ($line['Amount'] <= 0 ? "<td style='width: 5em;'></td>" . $amountCell : $amountCell . "<td style='width: 5em;'></td>") . "</tr>";
		}
		print "</table>";
	endif;

	if(!$isNew && !$bill['IsRepayment']):
		if(!is_array($_POST['newlines'])) $_POST['newlines'] = array();
		// Handle POST data
		if($_POST['newamount'] != 0) {
			// Charge to
			$total = count($_POST['charge']);
			if(is_array($_POST['charge']))
			foreach($_POST['charge'] as $userID=>$amount) {
				for($a = 1; $a <= $amount; $a++)
					array_push($_POST['newlines'], array("Description"=>$_POST['newdescription'], "UserID"=>$userID, "Amount"=>$_POST['newamount'], "Divisor"=>$total, "IsPayment"=>0));
			}
			// Paid by
			$total = count($_POST['paid']);
			if(is_array($_POST['paid']))
			foreach($_POST['paid'] as $userID=>$amount) {
				for($a = 1; $a <= $amount; $a++)
					array_push($_POST['newlines'], array("Description"=>$_POST['newdescription'], "UserID"=>$userID, "Amount"=>$_POST['newamount'], "Divisor"=>$total, "IsPayment"=>-1));
			}			
		}
		// Input form
			$groupUsers = $db->q("table SELECT ID, Login FROM Users_Groups LEFT JOIN Users ON Users_Groups.UserID = Users.ID WHERE GroupID = %i AND IsActive = -1", $bill['GroupID']);
		print "<h1 style='background-color: silver;'>Add lines</h1>";
		print "<form action='$PHP_SELF?id=$billID' method='post'><table>";
		print "<input type='hidden' name='deleteNew' value='-1'>";
		$i = $total = 0;
		for($i = 0; $i < count($_POST['newlines']); $i++) {
			$line = $_POST['newlines'][$i];
			$line['Amount'] = str_replace(',', '.', $line['Amount']);
			// Print the lines	
			$username = $db->q("value SELECT DisplayName FROM Users WHERE ID = %i", $line['UserID']);
			print "<tr" . ($i % 2 ? " class='gray'" : "") . "><td style='width: 15em;'><select name='newlines[$i][IsPayment]'><option value='0'" . ($line['IsPayment'] == 0 ? " selected='selected'" : "") . ">Charge to</option><option value='-1'" . ($line['IsPayment'] == -1 ? " selected='selected'" : "") . ">Paid by</option></select><select name='newlines[$i][UserID]'>";
			foreach($groupUsers as $u) print "<option value='{$u['ID']}'" . ($line['UserID'] == $u['ID'] ? " selected='selected'" : "") . ">{$u['Login']}</option>";
			print "</select></td><td><input type='text' name='newlines[$i][Description]' value=\"" . stripslashes($line['Description']) . "\" style='width: 100%;'></td><td style='width: 10em;'>1/<input type='text' size='1' maxlength='2' style='width: 1em;' name='newlines[$i][Divisor]' value='{$line['Divisor']}'> of &euro; <input type='text' size='5' name='newlines[$i][Amount]' style='width: 4em;' value='" . number_format($line['Amount'], 2) . "'></td></tr>";
			$total += ($line['IsPayment'] ? -1 : 1) * $line['Amount'] / $line['Divisor'];
		}
		print "<tr style='height: 10px;'><td colspan='5'></td></tr>";
		print "<tr valign='top' class='gray'><td><b><label for='newdescription' accesskey='N'><span class='accesskey'>N</span>ew line(s):</label></b> ";
		print "</td><td colspan='1'><input type='text' style='width: 100%;' value=\"" . stripslashes($bill['Description']) . "\" id='newdescription' name='newdescription'></td><td >&euro;&nbsp;<input type='text' size='10' name='newamount' style='width: 4em;'></td></tr>";
		print "<tr class='gray'><td></td><td colspan='3'><table><tr><th>Charge to:</th><th>Paid by:</th></tr><tr><td><ul class='checkboxlist'> ";
		foreach($groupUsers as $u) print "<li><input type='checkbox' value='1' name='charge[{$u['ID']}]' id='ulc{$u['ID']}'><label for='ulc{$u['ID']}'>{$u['Login']}</label></li>";
		print "</ul></td><td><ul class='checkboxlist'>";
		foreach($groupUsers as $u) print "<li><input type='checkbox' value='1' name='paid[{$u['ID']}]' id='ulp{$u['ID']}'><label for='ulp{$u['ID']}'>{$u['Login']}</label></li>";
		print "</ul></td></tr></table></td></tr>";
		print "<tr class='gray'><td colspan='4' style='text-align: center;'><input type='submit' name='updatenew' accesskey='D' value='Add to temporary balance'> </td></tr>";
		print "<tr style='height: 10px;'><td colspan='4'></td></tr>";
		print "<tr class='gray'><td colspan='2' style='text-align: right;'><b>Balance:</b>&nbsp;</td><td>" . money_format(moneyFormat, $total) . "</td></tr>";
		print "<tr class='gray'><td colspan='4' style='text-align: center;'> <input type='submit' name='savenew' accesskey='s' value='Save temporary balance to bill'" . (abs($total) < 1E-5 && count($_POST['newlines']) > 0 ? "" : " disabled='disabled'") . "></td></tr>";
		print "</table></form>";
	endif;

	if(!$isNew && !count($_POST['newlines'])) {	
		$groupMembers = $db->q("column SELECT UserID FROM Users_Groups WHERE GroupID = %i AND IsActive = -1", $bill['GroupID']);
		print "<h1>E-mail notification</h1>";
		print "<form action='$PHP_SELF?id=$billID' method='post'><table><tr><td>Check the members of the group you want to notify of this bill.</td></tr><tr><td><ul>";
		if($_POST['email']) {
			$message = "Dear #username,\n\n{$gUser['DisplayName']} would like to draw your attention to a " . ($bill['IsRepayment'] ? "repayment" : "bill") . " in the IOU system titled '{$bill['Description']}'. You can view the bill at " . getURL();
			foreach(array_keys($_POST['notify']) as $memberID) {
				$user = $db->q("tuple SELECT DisplayName, Email FROM Users WHERE ID = %i", $memberID);
				mail($user['Email'], "IOU Notification", str_replace('#username', $user['DisplayName'], $message), "From: {$gUser['DisplayName']} <{$gUser['Email']}>");
				print "<li>E-mail sent to {$user['DisplayName']}</li>";
			}
			print "</ul>";
		}
		else 
		{
			foreach($groupMembers as $memberID) {
				print "<li><input type='checkbox' name='notify[{$memberID}]' id='notify:$memberID'" . ($db->q("value SELECT COUNT(*) FROM Journal WHERE UserID = %i AND BillID = %i", $memberID, $billID) > 0 ? " checked='checked'" : "") . " value='1'><label for='notify:$memberID'>" . $db->q("value SELECT DisplayName FROM Users WHERE ID = %i", $memberID) . "</label></li>";
			}
			print "</ul></td></tr><tr><td><input type='submit' name='email' value='Send e-mail notification.'></td></tr>";
		}
		print "</td></tr></table>";
	}

	focusOn($isNew ? "date" : "newdescription");

	print_footer();
?>
